<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>贪吃蛇大作战 - 豪华版</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Arial', sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center;
            overflow: hidden;
        }

        .game-container {
            position: relative;
            background: rgba(255, 255, 255, 0.1);
            border-radius: 20px;
            padding: 20px;
            box-shadow: 0 8px 32px rgba(31, 38, 135, 0.37);
            backdrop-filter: blur(8px);
            border: 1px solid rgba(255, 255, 255, 0.18);
        }

        #gameCanvas {
            border: 3px solid #fff;
            border-radius: 10px;
            background: #000;
            display: block;
        }

        .ui-panel {
            position: absolute;
            top: 20px;
            left: 20px;
            color: white;
            font-size: 18px;
            z-index: 10;
        }

        .score {
            margin-bottom: 10px;
            text-shadow: 2px 2px 4px rgba(0,0,0,0.5);
        }

        .level {
            margin-bottom: 10px;
            text-shadow: 2px 2px 4px rgba(0,0,0,0.5);
        }

        .menu {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background: rgba(0, 0, 0, 0.9);
            padding: 40px;
            border-radius: 20px;
            text-align: center;
            color: white;
            z-index: 100;
            min-width: 400px;
        }

        .menu h1 {
            margin-bottom: 30px;
            font-size: 36px;
            background: linear-gradient(45deg, #ff6b6b, #4ecdc4);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
        }

        .menu button {
            display: block;
            width: 100%;
            padding: 15px;
            margin: 10px 0;
            background: linear-gradient(45deg, #667eea, #764ba2);
            color: white;
            border: none;
            border-radius: 10px;
            font-size: 18px;
            cursor: pointer;
            transition: transform 0.3s;
        }

        .menu button:hover {
            transform: scale(1.05);
        }

        .skin-selector {
            margin: 20px 0;
        }

        .skin-option {
            display: inline-block;
            width: 60px;
            height: 60px;
            margin: 5px;
            border-radius: 10px;
            cursor: pointer;
            transition: transform 0.3s;
            border: 3px solid transparent;
        }

        .skin-option:hover {
            transform: scale(1.1);
        }

        .skin-option.selected {
            border-color: #fff;
            transform: scale(1.1);
        }

        .level-selector {
            margin: 20px 0;
        }

        .level-option {
            display: inline-block;
            padding: 10px 20px;
            margin: 5px;
            background: rgba(255, 255, 255, 0.2);
            border-radius: 10px;
            cursor: pointer;
            transition: all 0.3s;
        }

        .level-option:hover {
            background: rgba(255, 255, 255, 0.3);
        }

        .level-option.selected {
            background: #4ecdc4;
            color: #000;
        }

        .leaderboard {
            margin-top: 20px;
            text-align: left;
        }

        .leaderboard h3 {
            margin-bottom: 10px;
            color: #4ecdc4;
        }

        .leaderboard-entry {
            padding: 5px 0;
            border-bottom: 1px solid rgba(255, 255, 255, 0.2);
        }

        .game-over {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background: rgba(0, 0, 0, 0.9);
            padding: 40px;
            border-radius: 20px;
            text-align: center;
            color: white;
            z-index: 100;
            min-width: 400px;
        }

        .game-over h2 {
            margin-bottom: 20px;
            color: #ff6b6b;
        }

        .game-over input {
            width: 100%;
            padding: 10px;
            margin: 10px 0;
            border-radius: 5px;
            border: none;
            font-size: 16px;
        }

        .power-up-indicator {
            position: absolute;
            top: 20px;
            right: 20px;
            color: white;
            font-size: 14px;
            text-align: right;
        }

        .particle {
            position: absolute;
            width: 4px;
            height: 4px;
            background: #fff;
            border-radius: 50%;
            pointer-events: none;
        }

        .combo-text {
            position: absolute;
            color: #ffff00;
            font-size: 24px;
            font-weight: bold;
            text-shadow: 2px 2px 4px rgba(0,0,0,0.8);
            pointer-events: none;
            animation: comboAnimation 1s ease-out forwards;
        }

        @keyframes comboAnimation {
            0% {
                opacity: 1;
                transform: scale(1) translateY(0);
            }
            100% {
                opacity: 0;
                transform: scale(1.5) translateY(-50px);
            }
        }

        .controls {
            position: absolute;
            bottom: 20px;
            left: 50%;
            transform: translateX(-50%);
            color: white;
            text-align: center;
            font-size: 14px;
        }

        .music-toggle {
            position: absolute;
            top: 20px;
            right: 100px;
            background: rgba(255, 255, 255, 0.2);
            border: none;
            color: white;
            padding: 10px;
            border-radius: 50%;
            cursor: pointer;
            font-size: 20px;
        }

        .music-toggle:hover {
            background: rgba(255, 255, 255, 0.3);
        }
    </style>
</head>
<body>
    <div class="game-container">
        <canvas id="gameCanvas" width="800" height="600"></canvas>
        
        <div class="ui-panel">
            <div class="score">得分: <span id="score">0</span></div>
            <div class="level">关卡: <span id="level">1</span></div>
            <div class="lives">生命: <span id="lives">3</span></div>
        </div>

        <div class="power-up-indicator">
            <div id="powerUpStatus"></div>
        </div>

        <button class="music-toggle" onclick="toggleMusic()">
            <i id="musicIcon" class="fas fa-volume-up"></i>
        </button>

        <div id="menu" class="menu">
            <h1>贪吃蛇大作战</h1>
            <button onclick="showSkinSelector()">选择皮肤</button>
            <button onclick="showLevelSelector()">选择关卡</button>
            <button onclick="showLeaderboard()">排行榜</button>
            <button onclick="startGame()">开始游戏</button>
            
            <div id="skinSelector" style="display: none;">
                <h3>选择皮肤</h3>
                <div class="skin-selector">
                    <div class="skin-option selected" style="background: linear-gradient(45deg, #00ff00, #00aa00)" onclick="selectSkin(0)"></div>
                    <div class="skin-option" style="background: linear-gradient(45deg, #ff0066, #ff6600)" onclick="selectSkin(1)"></div>
                    <div class="skin-option" style="background: linear-gradient(45deg, #0066ff, #00ccff)" onclick="selectSkin(2)"></div>
                    <div class="skin-option" style="background: linear-gradient(45deg, #ff00ff, #ff66ff)" onclick="selectSkin(3)"></div>
                    <div class="skin-option" style="background: linear-gradient(45deg, #ffff00, #ff9900)" onclick="selectSkin(4)"></div>
                </div>
                <button onclick="hideSkinSelector()">返回</button>
            </div>

            <div id="levelSelector" style="display: none;">
                <h3>选择关卡</h3>
                <div class="level-selector">
                    <div class="level-option selected" onclick="selectLevel(1)">关卡 1</div>
                    <div class="level-option" onclick="selectLevel(2)">关卡 2</div>
                    <div class="level-option" onclick="selectLevel(3)">关卡 3</div>
                    <div class="level-option" onclick="selectLevel(4)">关卡 4</div>
                    <div class="level-option" onclick="selectLevel(5)">关卡 5</div>
                </div>
                <button onclick="hideLevelSelector()">返回</button>
            </div>

            <div id="leaderboard" style="display: none;">
                <h3>排行榜</h3>
                <div id="leaderboardList"></div>
                <button onclick="hideLeaderboard()">返回</button>
            </div>
        </div>

        <div id="gameOver" class="game-over" style="display: none;">
            <h2>游戏结束</h2>
            <p>最终得分: <span id="finalScore">0</span></p>
            <p>最高连击: <span id="maxCombo">0</span></p>
            <input type="text" id="playerName" placeholder="输入您的名字" maxlength="10">
            <button onclick="saveScore()">保存成绩</button>
            <button onclick="restartGame()">再来一局</button>
            <button onclick="backToMenu()">返回主菜单</button>
        </div>
    </div>

    <div class="controls">
        使用方向键或WASD控制移动 | 空格键暂停
    </div>

    <script>
        // 游戏状态
        let gameState = 'menu'; // menu, playing, paused, gameOver
        let score = 0;
        let level = 1;
        let lives = 3;
        let selectedSkin = 0;
        let selectedLevel = 1;
        let snake = [];
        let direction = { x: 1, y: 0 };
        let food = {};
        let powerUps = [];
        let obstacles = [];
        let gameLoop;
        let combo = 0;
        let maxCombo = 0;
        let powerUpActive = null;
        let powerUpTimer = 0;
        let musicEnabled = true;
        let leaderboard = [];

        // 皮肤配置
        const skins = [
            { name: '经典绿', snakeColor: '#00ff00', foodColor: '#ff0000', bgColor: '#000000' },
            { name: '霓虹粉', snakeColor: '#ff0066', foodColor: '#00ffff', bgColor: '#1a001a' },
            { name: '海洋蓝', snakeColor: '#0066ff', foodColor: '#ffaa00', bgColor: '#001a33' },
            { name: '梦幻紫', snakeColor: '#ff00ff', foodColor: '#00ff00', bgColor: '#1a0033' },
            { name: '阳光黄', snakeColor: '#ffff00', foodColor: '#ff00ff', bgColor: '#331a00' }
        ];

        // 关卡配置
        const levels = [
            { speed: 150, obstacles: 0, foodCount: 1 },
            { speed: 130, obstacles: 3, foodCount: 1 },
            { speed: 110, obstacles: 5, foodCount: 2 },
            { speed: 90, obstacles: 7, foodCount: 2 },
            { speed: 70, obstacles: 10, foodCount: 3 }
        ];

        // 道具类型
        const powerUpTypes = [
            { type: 'doubleScore', color: '#ffff00', duration: 10000, name: '双倍积分' },
            { type: 'slowMotion', color: '#00ffff', duration: 8000, name: '减速' },
            { type: 'wallPass', color: '#ff00ff', duration: 10000, name: '穿墙' },
            { type: 'extraLife', color: '#00ff00', duration: 0, name: '额外生命' }
        ];

        // 初始化画布
        const canvas = document.getElementById('gameCanvas');
        const ctx = canvas.getContext('2d');
        const GRID_SIZE = 20;
        const TILE_COUNT = {
            x: canvas.width / GRID_SIZE,
            y: canvas.height / GRID_SIZE
        };

        // 初始化排行榜
        function initLeaderboard() {
            const saved = localStorage.getItem('snakeLeaderboard');
            if (saved) {
                leaderboard = JSON.parse(saved);
            }
            updateLeaderboardDisplay();
        }

        // 更新排行榜显示
        function updateLeaderboardDisplay() {
            const leaderboardList = document.getElementById('leaderboardList');
            leaderboardList.innerHTML = '';
            
            const sorted = [...leaderboard].sort((a, b) => b.score - a.score);
            sorted.slice(0, 10).forEach((entry, index) => {
                const div = document.createElement('div');
                div.className = 'leaderboard-entry';
                div.innerHTML = `${index + 1}. ${entry.name} - ${entry.score}分`;
                leaderboardList.appendChild(div);
            });
        }

        // 显示/隐藏菜单
        function showSkinSelector() {
            document.getElementById('skinSelector').style.display = 'block';
        }

        function hideSkinSelector() {
            document.getElementById('skinSelector').style.display = 'none';
        }

        function showLevelSelector() {
            document.getElementById('levelSelector').style.display = 'block';
        }

        function hideLevelSelector() {
            document.getElementById('levelSelector').style.display = 'none';
        }

        function showLeaderboard() {
            document.getElementById('leaderboard').style.display = 'block';
            updateLeaderboardDisplay();
        }

        function hideLeaderboard() {
            document.getElementById('leaderboard').style.display = 'none';
        }

        // 选择皮肤
        function selectSkin(skinIndex) {
            selectedSkin = skinIndex;
            document.querySelectorAll('.skin-option').forEach((option, index) => {
                option.classList.toggle('selected', index === skinIndex);
            });
        }

        // 选择关卡
        function selectLevel(levelIndex) {
            selectedLevel = levelIndex;
            document.querySelectorAll('.level-option').forEach((option, index) => {
                option.classList.toggle('selected', index === levelIndex - 1);
            });
        }

        // 初始化游戏
        function initGame() {
            snake = [
                { x: 10, y: 10 },
                { x: 9, y: 10 },
                { x: 8, y: 10 }
            ];
            direction = { x: 1, y: 0 };
            score = 0;
            combo = 0;
            maxCombo = 0;
            powerUpActive = null;
            powerUpTimer = 0;
            
            generateFood();
            generateObstacles();
            generatePowerUps();
            
            updateUI();
        }

        // 生成食物
        function generateFood() {
            const levelConfig = levels[selectedLevel - 1];
            for (let i = 0; i < levelConfig.foodCount; i++) {
                let newFood;
                do {
                    newFood = {
                        x: Math.floor(Math.random() * TILE_COUNT.x),
                        y: Math.floor(Math.random() * TILE_COUNT.y)
                    };
                } while (isOccupied(newFood.x, newFood.y));
                
                if (i === 0) {
                    food = newFood;
                }
            }
        }

        // 生成障碍物
        function generateObstacles() {
            obstacles = [];
            const levelConfig = levels[selectedLevel - 1];
            
            for (let i = 0; i < levelConfig.obstacles; i++) {
                let obstacle;
                do {
                    obstacle = {
                        x: Math.floor(Math.random() * TILE_COUNT.x),
                        y: Math.floor(Math.random() * TILE_COUNT.y)
                    };
                } while (isOccupied(obstacle.x, obstacle.y));
                
                obstacles.push(obstacle);
            }
        }

        // 生成道具
        function generatePowerUps() {
            powerUps = [];
            if (Math.random() < 0.3) {
                let powerUp;
                do {
                    powerUp = {
                        x: Math.floor(Math.random() * TILE_COUNT.x),
                        y: Math.floor(Math.random() * TILE_COUNT.y),
                        type: powerUpTypes[Math.floor(Math.random() * powerUpTypes.length)]
                    };
                } while (isOccupied(powerUp.x, powerUp.y));
                
                powerUps.push(powerUp);
            }
        }

        // 检查位置是否被占用
        function isOccupied(x, y) {
            return snake.some(segment => segment.x === x && segment.y === y) ||
                   obstacles.some(obstacle => obstacle.x === x && obstacle.y === y) ||
                   (food && food.x === x && food.y === y) ||
                   powerUps.some(powerUp => powerUp.x === x && powerUp.y === y);
        }

        // 游戏主循环
        function gameStep() {
            if (gameState !== 'playing') return;

            const head = { x: snake[0].x + direction.x, y: snake[0].y + direction.y };

            // 检查边界
            if (!powerUpActive || powerUpActive.type !== 'wallPass') {
                if (head.x < 0 || head.x >= TILE_COUNT.x || head.y < 0 || head.y >= TILE_COUNT.y) {
                    gameOver();
                    return;
                }
            } else {
                // 穿墙效果
                if (head.x < 0) head.x = TILE_COUNT.x - 1;
                if (head.x >= TILE_COUNT.x) head.x = 0;
                if (head.y < 0) head.y = TILE_COUNT.y - 1;
                if (head.y >= TILE_COUNT.y) head.y = 0;
            }

            // 检查碰撞
            if (snake.some(segment => segment.x === head.x && segment.y === head.y)) {
                gameOver();
                return;
            }

            // 检查障碍物碰撞
            if (obstacles.some(obstacle => obstacle.x === head.x && obstacle.y === head.y)) {
                gameOver();
                return;
            }

            snake.unshift(head);

            // 检查食物
            if (head.x === food.x && head.y === food.y) {
                score += powerUpActive && powerUpActive.type === 'doubleScore' ? 20 : 10;
                combo++;
                maxCombo = Math.max(maxCombo, combo);
                generateFood();
                generatePowerUps();
                createParticles(food.x * GRID_SIZE + GRID_SIZE/2, food.y * GRID_SIZE + GRID_SIZE/2);
                showCombo();
            } else {
                snake.pop();
                if (combo > 0) {
                    combo = 0;
                }
            }

            // 检查道具
            const powerUp = powerUps.find(p => p.x === head.x && p.y === head.y);
            if (powerUp) {
                activatePowerUp(powerUp);
                powerUps = powerUps.filter(p => p !== powerUp);
            }

            // 更新道具计时器
            if (powerUpActive && powerUpTimer > 0) {
                powerUpTimer -= levels[selectedLevel - 1].speed;
                if (powerUpTimer <= 0) {
                    powerUpActive = null;
                }
            }

            updateUI();
            draw();
        }

        // 激活道具
        function activatePowerUp(powerUp) {
            powerUpActive = powerUp.type;
            
            switch (powerUp.type.type) {
                case 'doubleScore':
                    powerUpTimer = powerUp.type.duration;
                    break;
                case 'slowMotion':
                    powerLoop();
                    break;
                case 'wallPass':
                    powerUpTimer = powerUp.type.duration;
                    break;
                case 'extraLife':
                    lives++;
                    powerUpActive = null;
                    break;
            }
        }

        // 创建粒子效果
        function createParticles(x, y) {
            for (let i = 0; i < 10; i++) {
                const particle = document.createElement('div');
                particle.className = 'particle';
                particle.style.left = x + 'px';
                particle.style.top = y + 'px';
                particle.style.background = skins[selectedSkin].foodColor;
                
                const angle = (Math.PI * 2 * i) / 10;
                const velocity = 5;
                const vx = Math.cos(angle) * velocity;
                const vy = Math.sin(angle) * velocity;
                
                document.querySelector('.game-container').appendChild(particle);
                
                let px = x;
                let py = y;
                const animate = () => {
                    px += vx;
                    py += vy;
                    particle.style.left = px + 'px';
                    particle.style.top = py + 'px';
                    particle.style.opacity = parseFloat(particle.style.opacity || 1) - 0.02;
                    
                    if (parseFloat(particle.style.opacity) > 0) {
                        requestAnimationFrame(animate);
                    } else {
                        particle.remove();
                    }
                };
                requestAnimationFrame(animate);
            }
        }

        // 显示连击
        function showCombo() {
            if (combo > 1) {
                const comboText = document.createElement('div');
                comboText.className = 'combo-text';
                comboText.textContent = `连击 x${combo}!`;
                comboText.style.left = (food.x * GRID_SIZE + GRID_SIZE/2) + 'px';
                comboText.style.top = (food.y * GRID_SIZE + GRID_SIZE/2) + 'px';
                
                document.querySelector('.game-container').appendChild(comboText);
                
                setTimeout(() => comboText.remove(), 1000);
            }
        }

        // 绘制游戏
        function draw() {
            // 清空画布
            ctx.fillStyle = skins[selectedSkin].bgColor;
            ctx.fillRect(0, 0, canvas.width, canvas.height);

            // 绘制网格
            ctx.strokeStyle = 'rgba(255, 255, 255, 0.1)';
            ctx.lineWidth = 1;
            for (let x = 0; x <= canvas.width; x += GRID_SIZE) {
                ctx.beginPath();
                ctx.moveTo(x, 0);
                ctx.lineTo(x, canvas.height);
                ctx.stroke();
            }
            for (let y = 0; y <= canvas.height; y += GRID_SIZE) {
                ctx.beginPath();
                ctx.moveTo(0, y);
                ctx.lineTo(canvas.width, y);
                ctx.stroke();
            }

            // 绘制蛇
            snake.forEach((segment, index) => {
                const gradient = ctx.createLinearGradient(
                    segment.x * GRID_SIZE, segment.y * GRID_SIZE,
                    (segment.x + 1) * GRID_SIZE, (segment.y + 1) * GRID_SIZE
                );
                
                if (index === 0) {
                    gradient.addColorStop(0, skins[selectedSkin].snakeColor);
                    gradient.addColorStop(1, adjustBrightness(skins[selectedSkin].snakeColor, -30));
                } else {
                    gradient.addColorStop(0, adjustBrightness(skins[selectedSkin].snakeColor, -20));
                    gradient.addColorStop(1, adjustBrightness(skins[selectedSkin].snakeColor, -40));
                }
                
                ctx.fillStyle = gradient;
                ctx.fillRect(segment.x * GRID_SIZE + 1, segment.y * GRID_SIZE + 1, 
                           GRID_SIZE - 2, GRID_SIZE - 2);
                
                // 蛇头眼睛
                if (index === 0) {
                    ctx.fillStyle = '#fff';
                    ctx.fillRect(segment.x * GRID_SIZE + 5, segment.y * GRID_SIZE + 5, 3, 3);
                    ctx.fillRect(segment.x * GRID_SIZE + 12, segment.y * GRID_SIZE + 5, 3, 3);
                }
            });

            // 绘制食物
            const foodGradient = ctx.createRadialGradient(
                food.x * GRID_SIZE + GRID_SIZE/2, food.y * GRID_SIZE + GRID_SIZE/2, 0,
                food.x * GRID_SIZE + GRID_SIZE/2, food.y * GRID_SIZE + GRID_SIZE/2, GRID_SIZE/2
            );
            foodGradient.addColorStop(0, skins[selectedSkin].foodColor);
            foodGradient.addColorStop(1, adjustBrightness(skins[selectedSkin].foodColor, -30));
            ctx.fillStyle = foodGradient;
            ctx.beginPath();
            ctx.arc(food.x * GRID_SIZE + GRID_SIZE/2, food.y * GRID_SIZE + GRID_SIZE/2, 
                   GRID_SIZE/2 - 2, 0, Math.PI * 2);
            ctx.fill();

            // 绘制障碍物
            ctx.fillStyle = '#666';
            obstacles.forEach(obstacle => {
                ctx.fillRect(obstacle.x * GRID_SIZE + 2, obstacle.y * GRID_SIZE + 2, 
                           GRID_SIZE - 4, GRID_SIZE - 4);
            });

            // 绘制道具
            powerUps.forEach(powerUp => {
                ctx.fillStyle = powerUp.type.color;
                ctx.beginPath();
                ctx.arc(powerUp.x * GRID_SIZE + GRID_SIZE/2, powerUp.y * GRID_SIZE + GRID_SIZE/2, 
                       GRID_SIZE/3, 0, Math.PI * 2);
                ctx.fill();
                
                // 道具发光效果
                ctx.shadowColor = powerUp.type.color;
                ctx.shadowBlur = 10;
                ctx.beginPath();
                ctx.arc(powerUp.x * GRID_SIZE + GRID_SIZE/2, powerUp.y * GRID_SIZE + GRID_SIZE/2, 
                       GRID_SIZE/4, 0, Math.PI * 2);
                ctx.fill();
                ctx.shadowBlur = 0;
            });
        }

        // 调整颜色亮度
        function adjustBrightness(color, amount) {
            const num = parseInt(color.replace('#', ''), 16);
            const r = Math.max(0, Math.min(255, (num >> 16) + amount));
            const g = Math.max(0, Math.min(255, ((num >> 8) & 0x00FF) + amount));
            const b = Math.max(0, Math.min(255, (num & 0x0000FF) + amount));
            return `#${((r << 16) | (g << 8) | b).toString(16).padStart(6, '0')}`;
        }

        // 更新UI
        function updateUI() {
            document.getElementById('score').textContent = score;
            document.getElementById('level').textContent = selectedLevel;
            document.getElementById('lives').textContent = lives;
            
            const statusDiv = document.getElementById('powerUpStatus');
            if (powerUpActive) {
                const timeLeft = Math.ceil(powerUpTimer / 1000);
                statusDiv.innerHTML = `道具: ${powerUpActive.type.name} (${timeLeft}s)`;
            } else {
                statusDiv.innerHTML = '';
            }
        }

        // 开始游戏
        function startGame() {
            gameState = 'playing';
            document.getElementById('menu').style.display = 'none';
            initGame();
            gameLoop = setInterval(gameStep, levels[selectedLevel - 1].speed);
        }

        // 游戏结束
        function gameOver() {
            gameState = 'gameOver';
            clearInterval(gameLoop);
            document.getElementById('finalScore').textContent = score;
            document.getElementById('maxCombo').textContent = maxCombo;
            document.getElementById('gameOver').style.display = 'block';
        }

        // 保存分数
        function saveScore() {
            const name = document.getElementById('playerName').value.trim() || '匿名玩家';
            leaderboard.push({ name, score, level: selectedLevel, date: new Date().toLocaleDateString() });
            leaderboard.sort((a, b) => b.score - a.score);
            leaderboard = leaderboard.slice(0, 10);
            
            localStorage.setItem('snakeLeaderboard', JSON.stringify(leaderboard));
            updateLeaderboardDisplay();
            restartGame();
        }

        // 重新开始
        function restartGame() {
            document.getElementById('gameOver').style.display = 'none';
            document.getElementById('playerName').value = '';
            startGame();
        }

        // 返回主菜单
        function backToMenu() {
            gameState = 'menu';
            document.getElementById('gameOver').style.display = 'none';
            document.getElementById('menu').style.display = 'block';
            document.getElementById('playerName').value = '';
        }

        // 切换音乐
        function toggleMusic() {
            musicEnabled = !musicEnabled;
            const icon = document.getElementById('musicIcon');
            icon.className = musicEnabled ? 'fas fa-volume-up' : 'fas fa-volume-mute';
        }

        // 键盘控制
        document.addEventListener('keydown', (e) => {
            if (gameState !== 'playing') return;
            
            switch(e.key) {
                case 'ArrowUp':
                case 'w':
                case 'W':
                    if (direction.y === 0) direction = { x: 0, y: -1 };
                    break;
                case 'ArrowDown':
                case 's':
                case 'S':
                    if (direction.y === 0) direction = { x: 0, y: 1 };
                    break;
                case 'ArrowLeft':
                case 'a':
                case 'A':
                    if (direction.x === 0) direction = { x: -1, y: 0 };
                    break;
                case 'ArrowRight':
                case 'd':
                case 'D':
                    if (direction.x === 0) direction = { x: 1, y: 0 };
                    break;
                case ' ':
                    if (gameState === 'playing') {
                        gameState = 'paused';
                        clearInterval(gameLoop);
                    } else if (gameState === 'paused') {
                        gameState = 'playing';
                        gameLoop = setInterval(gameStep, levels[selectedLevel - 1].speed);
                    }
                    e.preventDefault();
                    break;
            }
        });

        // 初始化
        initLeaderboard();
        draw();
    </script>
</body>
</html>
